package com.shengde.jinwawaforleader.model.myJob.everyRecipe;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.shengde.jinwawaforleader.HomeApplication;
import com.shengde.jinwawaforleader.R;
import com.shengde.jinwawaforleader.base.BaseActivity;
import com.shengde.jinwawaforleader.network.BaseProtocol;
import com.shengde.jinwawaforleader.network.protocolbean.ProUploadImg;
import com.shengde.jinwawaforleader.utils.LGImgCompressor;
import com.shengde.jinwawaforleader.views.ActionSheetDialog;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;


public class ModifyTheMenuActivity extends BaseActivity implements LGImgCompressor.CompressListener {
	private static final String TAG = "ModifyTheMenuActivity";
	private static final int FINSH = 1;
	String img;
	String mUrl;
	String content;
	String path ;
	public String date;
	public String title;
	ImageView imageView_listitem;
	TextView textView2;
	TextView textView1;

	EditText editText1;
	String string;
	public String string1;
	public int id;
	public static final int REQUEST_CODE_ALBUM = 100;
	public static final int REQUEST_CODE_CAMERA = 200;
	private TextView tv_back, fill_add, tv_title;
	private ModifyTheMenuActivity activity;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case FINSH:
					BaseProtocol.getInstance().modifyRecipe(mUrl, activity);
					break;
			}
		}
	};
	private String url;

	@Override
	public void onRoot(Bundle savedInstanceState) {
		setContentView(R.layout.activity_modify_the_menu);
		activity = ModifyTheMenuActivity.this;
	}

	@Override
	public void initView() {
		imageView_listitem = (ImageView) findViewById(R.id.imageView_listitem);
		textView2 = (TextView) findViewById(R.id.textView_grid_item00);
		textView1 = (TextView) findViewById(R.id.textView_grid_item);
		editText1 = (EditText) findViewById(R.id.editText1);
		tv_back = (TextView) findViewById(R.id.tv_back);
		fill_add = (TextView) findViewById(R.id.fill_add);
		tv_title = (TextView) findViewById(R.id.tv_title);
	}

	@Override
	public void initData() {
		img = this.getIntent().getStringExtra("img");//图片
		content = this.getIntent().getStringExtra("content");//: "蛋炒饭"
		date = this.getIntent().getStringExtra("date");//: "2016-05-23",
		title = this.getIntent().getStringExtra("title");//: "午餐",
		id = this.getIntent().getIntExtra("id", 0);//: "午餐",
		Log.i(TAG, "initData: id= " + id);
		textView1.setText(content + "");
		textView2.setText(title + "");
		tv_title.setText(getString(R.string.modify_recipe));
		fill_add.setText(getString(R.string.sure));
		url = BaseProtocol.IMG_BASE + img;
		Glide.with(this).load(url).into(imageView_listitem);
	}

	@Override
	public void initListener() {
		tv_back.setOnClickListener(this);
		imageView_listitem.setOnClickListener(this);
		fill_add.setOnClickListener(this);
	}

	@Override
	public void onWidgetClick(View view) {
		switch (view.getId()) {
			case R.id.tv_back:
				finish();
				break;
			case R.id.imageView_listitem:
				new ActionSheetDialog(ModifyTheMenuActivity.this)
						.builder()
						.setTitle("请选择操作")
						.setCancelable(false)
						.setCanceledOnTouchOutside(false)
						.addSheetItem("相册", ActionSheetDialog.SheetItemColor.Black,
								new ActionSheetDialog.OnSheetItemClickListener() {
									@Override
									public void onClick(int which) {
										Intent intent = new Intent();
										intent.setAction(Intent.ACTION_PICK);
										intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
										startActivityForResult(intent, REQUEST_CODE_ALBUM);

									}
								})
						.addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Black,
								new ActionSheetDialog.OnSheetItemClickListener() {
									@Override
									public void onClick(int which) {

										startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), REQUEST_CODE_CAMERA);

									}
								}).show();
				break;
			case R.id.fill_add:
				string1 = editText1.getText().toString().trim();
				if (TextUtils.isEmpty(string1)) {
					HomeApplication.showToastShort("菜名不能为空");
					return;
				}
				compressImage();
				break;
		}
	}

	/**
	 * 压缩图片
	 */
	private void compressImage() {
		if ("".equals(path) || path == null) {
			Log.i(TAG, "compressImage: url = " + url);
			BaseProtocol.getInstance().modifyRecipe(img, activity);
		} else {
			Log.i(TAG, "compressImage: path = " + path);
			LGImgCompressor.getInstance(ModifyTheMenuActivity.this).withListener(ModifyTheMenuActivity.this).
					starCompress(Uri.fromFile(new File(path)).toString(), 600, 800, 100);

		}

	}


	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CODE_ALBUM) {
			if (resultCode == RESULT_OK) {
				if (data != null) {
					Uri uriPath = data.getData();

					if (!"".equals(uriPath.getAuthority())) {
						Cursor cursor = getContentResolver().query(uriPath,
								new String[]{MediaStore.Images.Media.DATA},
								null, null, null);
						cursor.moveToFirst();
						path = cursor.getString(cursor
								.getColumnIndex(MediaStore.Images.Media.DATA));
						cursor.close();
					} else {
						path = uriPath.getPath();
					}
					Glide.with(this).load(path).into(imageView_listitem);

				}
			}
		} else if (requestCode == REQUEST_CODE_CAMERA) {
			if (resultCode == RESULT_OK) {
				Bitmap bm = (Bitmap) data.getExtras().get("data");
				Date date = new Date();
				File file = new File("sdcard/cache/");
				if (!file.exists()) {
					file.mkdir();
				}
				final File myCaptureFile = new File("sdcard/cache/"
						+ date.getTime() + ".jpg");
				try {
					BufferedOutputStream bos = new BufferedOutputStream(
							new FileOutputStream(myCaptureFile));
					/* 采用压缩转档方法 */
					bm.compress(Bitmap.CompressFormat.JPEG, 40, bos);
					/* 调用flush()方法，更新BufferStream */
					bos.flush();
					/* 结束OutputStream */
					bos.close();
					path = myCaptureFile.getAbsolutePath();

					Glide.with(this).load(path).into(imageView_listitem);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 上传图片
	 *
	 * @param path 压缩后图片的路径
	 */
	private void showUploadPic(String path) {

		String url = BaseProtocol.IMG_UPLOAD_HOST;
		RequestParams params = BaseProtocol.getRequestParams(url);
		params.addHeader("User-Agent", "SOHUWapRebot");
		params.addHeader("Accept-Language", "zh-cn,zh;q=0.5");
		params.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.7");
		params.addHeader("Connection", "keep-alive");
		params.setMultipart(true);
		params.addBodyParameter("pic", new File(path));
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				ProUploadImg pro_class_status = new Gson().fromJson(result, ProUploadImg.class);
				Log.i(TAG, "onSuccess: code" + pro_class_status.getCode());
				if (pro_class_status != null && pro_class_status.getCode() == 0) {
					List<String> mUrlList = pro_class_status.getUrl();
					if (mUrlList.size() > 0) {
						mUrl = mUrlList.get(0);
						Log.i(TAG, "onSuccess: mUrl" + mUrl);
					}
					mHandler.sendEmptyMessage(FINSH);

				}

			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {

			}
		});

	}

	@Override
	public void onCompressStart() {
		Log.d(TAG, "onCompressStart");

	}

	@Override
	public void onCompressEnd(LGImgCompressor.CompressResult compressResult) {
		Log.d(TAG, "onCompressEnd outPath:" + compressResult.getOutPath());
		if (compressResult.getStatus() == LGImgCompressor.CompressResult.RESULT_ERROR)//压缩失败
			return;

		File file = new File(compressResult.getOutPath());
		Bitmap bitmap = null;
		try {
			bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.fromFile(file));
			float imageFileSize = file.length() / 1024f;
			Log.i(TAG, "onCompressEnd:imageInfo " + "image info width:" + bitmap.getWidth() + " \nheight:" + bitmap.getHeight() +
					" \nsize:" + imageFileSize + "kb" + "\nimagePath:" + file.getAbsolutePath());
			path = file.getAbsolutePath();
			Log.i(TAG, "onCompressEnd: imagePath_one = " + file.getAbsolutePath());
			Log.i(TAG, "onCompressEnd: imagePath_two = " + compressResult.getOutPath());
			showUploadPic(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
